import { createResource } from "solid-js";
import { IndexColumn, Table, TableColumn } from "solid-table-context";
import { handleException } from "../services/utils";
import { RouteStateDto } from "../services/client";
import { useClientApi } from "../services";
import { ErrorBoundary, Show } from "solid-js";
import Loading from "~/components/Loading";

export default () => {
  const [data, { refetch }] = createResource(() => {
    return useClientApi()
      .getCurrentRoutes()
      .catch((err) => {
        handleException(err);
        return [] as RouteStateDto[];
      });
  });

  return (
    <ErrorBoundary
      fallback={
        <button type="button" onClick={() => refetch()}>
          Try again
        </button>
      }
    >
      <div class="flex flex-1 px-2">
        <button
          type="button"
          class="d-btn"
          disabled={data.loading}
          onClick={() => refetch()}
        >
          刷新
        </button>
      </div>
      <Loading show={data.loading}>
        <Table datas={data()} class="d-table">
          <IndexColumn header="No." />
          <TableColumn name={"routeId"} header="Route ID" />
          <TableColumn name={"clusterId"} header="Cluster" />
          <TableColumn header="Available">
            {(data: RouteStateDto) =>
              `${data.availableDestinationsCount}/${data.allDestinationsCount}`
            }
          </TableColumn>
        </Table>
      </Loading>
    </ErrorBoundary>
  );
};
